package com.ys.service.sys.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import com.ys.entity.sys.SysButton;
import com.ys.entity.sys.SysMenu;
import com.ys.mapper.sys.SysButtonMapper;
import com.ys.mapper.sys.SysMapper;
import com.ys.service.sys.SysButtonService;
import com.ys.vo.R;
import com.ys.vo.W;

@Service("sysButtonService")
public class SysButtonServiceImpl implements SysButtonService {

	@Autowired
	private SysMapper sysMapper;
	@Autowired
	private SysButtonMapper sysButtonMapper;

	@Override
	public R addSysButton(Long menuId, String name, String event, String nameShiroAuth) {

		if (menuId == null) {
			return R.error("菜单ID不能为空");
		} else if (new SysMenu().setId(menuId).count() == 0) {
			return R.error("菜单不存在");
		}
		
		if (name == null || name.length() == 0) {
			return R.error("字段名称不能为空");
		}
		
		if (event == null || event.length() == 0) {
			return R.error("事件编码不能为空");
		}
		
		if (nameShiroAuth == null || nameShiroAuth.length() == 0) {
			return R.error("权限编码不能为空");
		}
		
		String icon = null;
		Integer sortNo = 1;
		SysButton sysButton = SysButton.sysButton(menuId, name, event, icon, nameShiroAuth, sortNo, 1);
		sysButtonMapper.insert(sysButton);
		
		return R.ok("操作成功");
	}

	@Override
	@Transactional
	public R deleteTrue(Long id) {
		if (id == null) {
			return R.error("ID不能为空");
		}
		
		// 删除角色-按钮
		sysMapper.deleteTrueSysRoleButtonBySysButtonId(id);
		
		// 删除按钮
		sysButtonMapper.deleteTrue(id);
		
		return R.ok();
	}

	@Override
	public String toAddSysButton(Model model, Long sysMenuId) {
		
		if (sysMenuId == null) {
			return W.error(model, "菜单ID不能为空");
		}
		SysMenu sysMenu = new SysMenu().setId(sysMenuId).queryFirst();
		
		ToAddSysButtonDto dto = new ToAddSysButtonDto(sysMenu.getId(), sysMenu.getName());
		model.addAttribute("dto", dto);
		return "sys/sysButton/toAddSysButton";
	}

	@Override
	public R editSysButton(Long id, String name, String event, String nameShiroAuth) {

		SysButton entity = new SysButton().setId(id).queryFirst();
		entity.setNameShiroAuth(nameShiroAuth);
		sysButtonMapper.update(entity);
		
		return R.ok();
	}

	@Override
	public String toEditSysButton(Model model, Long id) {

		SysButton entity = new SysButton().setId(id).queryFirst();
		
		String name = entity.getName();
		String event = entity.getEvent();
		String nameShiroAuth = entity.getNameShiroAuth();
		ToEditSysButtonDto dto = new ToEditSysButtonDto(id, name, event, nameShiroAuth);
		model.addAttribute("dto", dto);
		return "sys/sysButton/toEditSysButton";
	}
}
